package com.tianming.wy.cmn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianming.wy.cmn.mapper.MenuMapper;
import com.tianming.wy.cmn.service.MenuService;
import com.tianming.wy.model.cmn.Dict;
import com.tianming.wy.model.cmn.Menu;
import com.tianming.wy.vo.cmn.MenuEeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

	@Autowired
	private MenuMapper menuMapper;

	/**
	 * 根据上级id获取子节点数据列表
	 * allEntries = true: 方法调用后清空所有缓存
	 * beforeInvocation = true：方法调用前清空所有缓存
	 *
	 */
	@Cacheable(value = "menu", keyGenerator = "keyGenerator")
	@Override
	public List<Menu> getUserMenus() {
		List<Menu> menuList = menuMapper.selectList(new QueryWrapper<Menu>());
		menuList.stream().forEach(menu -> {
			boolean isHasChildren = this.isHasChildren(menu.getId());
			menu.setHasChildren(isHasChildren);
		});
		return menuList;
	}

	@Override
	public IPage<Menu> queryMenus(MenuEeVo menuEeVo) {
		Page<Menu> pageParam = new Page<>(menuEeVo.getCurrent(), menuEeVo.getSize());
		IPage<Menu> pages = menuMapper.queryMenus(pageParam, menuEeVo);
		return pages;
	}

	/**
	 * 判断该节点是否有子节点
	 *
	 * @param id
	 * @return
	 */
	private boolean isHasChildren(Long id) {
		Integer count = menuMapper.selectCount(new QueryWrapper<Menu>().eq("parent_id", id));
		if (count.intValue() > 0) {
			return true;
		}
		return false;
	}

	@CacheEvict(value = "menu", allEntries=true)
	@Override
	public boolean saveBatch(Collection<Menu> entityList) {
		return super.saveBatch(entityList);
	}
}
